package meiyunting.shiwuzhaoling.controller;

import meiyunting.shiwuzhaoling.client.ActivityServiceClient;
import meiyunting.shiwuzhaoling.service.SimpleCircuitBreaker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户活动控制器
 * 演示微服务间通信
 */
@RestController
@RequestMapping("/api/users")
public class UserActivitiesController {

    @Autowired
    private ActivityServiceClient activityServiceClient;
    
    @Autowired
    private SimpleCircuitBreaker circuitBreaker;

    /**
     * 获取用户参与的活动
     * 通过Feign客户端调用活动报名服务
     * @param userId 用户ID
     * @return 活动列表
     */
    @GetMapping("/{userId}/activities")
    public Map<String, Object> getUserActivities(@PathVariable Long userId) {
        // 使用自定义断路器执行服务调用
        List<Map<String, Object>> activities = circuitBreaker.execute(
            "activity-service",
            () -> activityServiceClient.getUserActivities(userId),
            () -> Collections.emptyList()
        );
        
        Map<String, Object> result = new HashMap<>();
        result.put("userId", userId);
        result.put("activities", activities);
        result.put("count", activities.size());
        result.put("source", "lost-found-service");
        
        return result;
    }

    /**
     * 服务通信测试端点
     * @return 测试结果
     */
    @GetMapping("/service-communication-test")
    public Map<String, Object> testServiceCommunication() {
        Map<String, Object> result = new HashMap<>();
        result.put("status", "UP");
        result.put("message", "服务间通信测试端点");
        result.put("service", "lost-found-service");
        result.put("target_services", new String[]{"activity-service", "market-service", "library-service"});
        result.put("circuit_breaker", "simple-implementation");
        return result;
    }
} 